﻿using Abp.AspNetCore.Mvc.Controllers;
using Abp.Dependency;
using Abp.Domain.Entities;
using Abp.Web.Models;
using Batman.Cms.Core.Services;
using Batman.Core;
using Batman.Core.Utils;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Linq;
using System.Security.Claims;

namespace Batman.Cms.Core.Controllers
{
    public class BatmanController<T> : AbpController where T : Entity<string>
    {
        public IocManager IocManager { get; set; }

        public BatmanController()
        {
            
        }

        #region 过滤限制默认方法

        /// <summary>
        /// 构建404未找到返回实体
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        private void Build404NotFoundBody(HttpResponse response)
        {
            var ajaxResponse = new AjaxResponse()
            {
                Success = false,
                Error = new ErrorInfo(404, "接口不存在")
            };
            response.Body = StreamUtil.ToStream(ajaxResponse);
        }

        /// <summary>
        ///  限制的方法列表
        /// </summary>
        public static readonly string[] MethodScope = new string[] { "page", "create", "update", "delete" };

        #endregion

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var action = context.RouteData.Values["action"].ToString().ToLower();
            if (MethodScope.Contains(action))
            {
                var methodControl = GetType().GetCustomAttributes(true).ToList().OfType<MethodControlAttribute>().FirstOrDefault();
                if (methodControl == null)
                {
                    base.OnActionExecuting(context);
                    return;
                }

                switch (action)
                {
                    case "page":
                        if (!methodControl.PageMethod)
                            Build404NotFoundBody(context.HttpContext.Response);
                        return;
                    case "create":
                        if (!methodControl.CreateMethod)
                            Build404NotFoundBody(context.HttpContext.Response);
                        return;
                    case "update":
                        if (!methodControl.UpdateMethod)
                            Build404NotFoundBody(context.HttpContext.Response);
                        return;
                    case "delete":
                        if (!methodControl.DeleteMethod)
                            Build404NotFoundBody(context.HttpContext.Response);
                        return;
                }
            }

            base.OnActionExecuting(context);
        }

        public BaseReader<T> Reader { get; set; }

        public BaseManager<T> BaseManager { get; set; }
    }

    public static class Extensions
    {

        public static string GetUserId(this ClaimsPrincipal user)
        {
            return user.Identity.Name;
        }
    }

}
